package iamdev.me.ytds.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import iamdev.me.ytds.entity.RegisterMail;
import iamdev.me.ytds.entity.User;
import iamdev.me.ytds.exception.SystemException;
import iamdev.me.ytds.mapper.RegisterMailMapper;
import iamdev.me.ytds.mapper.UserMapper;
import iamdev.me.ytds.service.IMailService;
import iamdev.me.ytds.service.IUserService;
import iamdev.me.ytds.utils.HashUtil;
import jodd.util.RandomString;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zxc
 * @since 2018-06-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private Logger logger =LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RegisterMailMapper registerMailMapper;
    @Autowired
    private IMailService mailService;

    @Override
    public User login(String name, String pwd){
        EntityWrapper<User>ew=new EntityWrapper<>();
        ew.eq("user_name",name);
        User user = this.selectOne(ew);
        if(user==null){
            return null;
        }else {
            String hashResult = HashUtil.sha256(user.getUserSalt()+pwd);
            if(user.getUserPwd().equals(hashResult)){
                user.setUserToken(IdWorker.get32UUID());
                this.updateById(user);
                return user;
            }
        }
        return null;
    }
    @Override
    public boolean existUserByName(String name){
        EntityWrapper<User>ew=new EntityWrapper<>();
        ew.eq("user_name",name);
        User user = this.selectOne(ew);
        if(user==null){
            return false;
        }else {
            return true;
        }
    }
    @Override
    public boolean existUserByEmail(String email){
        EntityWrapper<User>ew=new EntityWrapper<>();
        ew.eq("user_mail",email);
        User user = this.selectOne(ew);
        if(user==null){
            return false;
        }else {
            return true;
        }
    }

    @Override
    public void sendRegisterEmail(String email){
        String code = new RandomString(System.currentTimeMillis()).randomNumeric(6);
        RegisterMail registerMail =new RegisterMail();
        registerMail.setCode(code);
        registerMail.setEmail(email);
        registerMail.setSendDate(new Date());
        registerMailMapper.insert(registerMail);
        mailService.sendMail("云图文档搜索,欢迎注册用户,这是你的注册码",String.format("您的注册验证码为%s。10分钟内有效。如非您本人操作，可忽略本消息。",code),email);
    }
    @Override
    public User registerUser(User user, String mailCode){
        if(existUserByName(user.getUserName())){
            throw new SystemException("用户名已存在");
        }
        if(existUserByEmail(user.getUserMail())){
            throw new SystemException("该邮箱已存在");
        }
        if(StringUtils.isEmpty(mailCode)){
            throw new SystemException("邮箱验证码不存在");
        }
        if(StringUtils.isEmpty(user.getNickName())){
            throw new SystemException("昵称不能为空");
        }
        if(StringUtils.isEmpty(user.getUserPwd())){
            throw new SystemException("密码不能为空");
        }
        Date now=new Date();

        EntityWrapper<RegisterMail> ew=new EntityWrapper<>();
        ew.eq("code",mailCode);
        ew.eq("email",user.getUserMail());
        ew.gt("send_date",DateUtils.addMinutes(now,-10));
        List<RegisterMail> registerMailList = registerMailMapper.selectList(ew);
        long count = registerMailList.stream().filter(registerMail -> {
           if(registerMail.getCode().equals(mailCode)){
               return true;
           }else {
               return false;
           }
        }).count();
        if(count>0){
            user.setUserToken(null);
            user.setRegisterDate(new Date());
            user.setUserSalt(IdWorker.get32UUID());
            user.setUserPwd(HashUtil.sha256(user.getUserSalt()+user.getUserPwd()));
            this.insert(user);
        }
        return user;
    }


    @Override
    public User findUserByToken(String token){
        EntityWrapper<User>ew=new EntityWrapper<>();
        ew.eq("user_token",token);
        User user = this.selectOne(ew);
        return user;
    }

}
